package com.example.demo.controller;


import com.example.demo.mapper.DialogMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.Connection;
import com.example.demo.pojo.User;
import com.example.demo.service.Impl.ConnectionServiceImpl;
import com.example.demo.service.Impl.DialogServiceImpl;
import com.example.demo.util.getHttpSessionConfigurator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = getHttpSessionConfigurator.class)
@Component
public class ChatController {


    private static Map<String,Session> map=new ConcurrentHashMap<>();

    private static UserMapper userMapper;

    private static DialogServiceImpl dialogService;

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        ChatController.userMapper=userMapper;
    }

    private static ConnectionServiceImpl connectionService;

    @Autowired
    public void setConnectionServiceImpl(ConnectionServiceImpl connectionService){
        ChatController.connectionService=connectionService;
    }

    @Autowired
    public void setDialogServiceImpl(DialogServiceImpl dialogService){
        ChatController.dialogService=dialogService;
    }

    EndpointConfig config;


    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        this.config=config;
        HttpSession httpSession=(HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        int id=(Integer) httpSession.getAttribute("user");
        String name=userMapper.getUserById(id).getUsername();
        Connection connection=connectionService.getConnection(id);
        if(connection==null) return;
        map.put(name,session);
        //System.out.println("id="+id+"name="+name);


    }
    @OnMessage
    public void onMessage(String message,Session session){
        HttpSession httpSession=(HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        int id=(Integer) httpSession.getAttribute("user");
        User user=userMapper.getUserById(id);
        String name=user.getUsername();
        Connection connection=connectionService.getConnection(id);
        if(connection==null) return;

        dialogService.insertDialog(user,message,connection.getConnection_id());

        System.out.println(name);
        String toName=(name.equals(connection.getSend_user_name()))?connection.getReceive_user_name():connection.getSend_user_name();

        System.out.println("toName="+toName);
        Session toSession=map.get(toName);
        try {
            if(toSession!=null&& session.isOpen()){
                System.out.println(message);
                this.sendMessage(message,toSession);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //System.out.println("message"+session);
    }
    private void sendMessage(String message, Session toSession) {
        try {
            System.out.println(toSession.isOpen());
            if(toSession.isOpen())
                toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
